//获取url中的参数方法
import html2canvas from 'html2canvas'
function getUrlParam(url, name) {
    //构造一个含有目标参数的正则表达式对象
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    //匹配目标参数
    let urlStr = url ? new URL(url).search : window.location.search
    var r = urlStr.substr(1).match(reg);
    //返回参数
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
}
// 去掉多余的0
function cutZero(num) {
    //拷贝一份 返回去掉零的新串
    let newstr = num;
    //循环变量 小数部分长度
    console.log(num.indexOf('.') - 1);
    let leng = num.length - num.indexOf('.') - 1;
    //判断是否有效数
    if (num.indexOf('.') > -1) {
        //循环小数部分
        for (let i = leng; i > 0; i--) {
            //如果newstr末尾有0
            if (
                newstr.lastIndexOf('0') > -1 &&
                newstr.substr(newstr.length - 1, 1) == 0
            ) {
                let k = newstr.lastIndexOf('0');
                //如果小数点后只有一个0 去掉小数点
                if (newstr.charAt(k - 1) == '.') {
                    return newstr.substring(0, k - 1);
                } else {
                    //否则 去掉一个0
                    newstr = newstr.substring(0, k);
                }
            } else {
                //如果末尾没有0
                return newstr;
            }
        }
    }
    return num;
}
function checkUrl(string) {
    let givenURL;
    try {
        givenURL = new URL(string);
    } catch (error) {
        console.log("error is", error);
        return false;
    }
    return true;
}
function splitAddress(address, index) {
    if (address) {
        if(address.length>15){
        let i = index ? (index - 1) : 4
        return (
            address.slice(0, index - 1 || 5) +
            "..." +
            address.slice(address.length - i, address.length)
        );
        }else{
            return address
        }

    } else {
        return '';
    }
};

const getAudioVideo = (constraintsData) => {
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }
    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先，如果有getUserMedia的话，就获得它
            var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
            // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
            if (!getUserMedia) {
                return Promise.reject({ code: 404 });
            }

            // 否则，为老的navigator.getUserMedia方法包裹一个Promise

            return new Promise(function (resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject);
            });
        }
    }
    return navigator.mediaDevices.getUserMedia(constraintsData)
}
const getDate = (time, format) => {
    let date = time ? new Date(time) : new Date();
    let year = date.getFullYear(); //获取当前年份
    let mon = date.getMonth() + 1; //获取当前月份
    let da = date.getDate(); //获取当前日
    let h = date.getHours(); //获取小时
    let m = date.getMinutes(); //获取分钟
    let s = date.getSeconds(); //获取秒
    if (format == 'YYYY-MM-DD') {
        return `${year}-${mon >= 10 ? mon : ('0' + mon)}-${da >= 10 ? da : ('0' + da)}`;
    }
    return `${year}-${mon >= 10 ? mon : ('0' + mon)}-${da >= 10 ? da : ('0' + da)} ${h >= 10 ? h : ('0' + h)}:${m >= 10 ? m : ('0' + m)}:${s >= 10 ? s : ('0' + s)}`;
};
function formatDate(days) {
    let date = new Date(days)
    const now = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    if (year === now.getFullYear()) {
        return `${month}-${day} ${hour}:${minute}`;
    } else {
        return `${year}-${month}-${day} ${hour}:${minute}`;
    }
}
const intervalTime = (date) => {
    date = date * 1000
    //计算出相差天数
    var days = Math.floor(date / (24 * 3600 * 1000));
    //计算出小时数
    var leave1 = date % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000));
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000));

    //计算相差秒数

    var leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000);
    return (days > 0 ? (days + "天 ") : '') + (hours > 0 ? (hours + "小时") : '') + (minutes > 0 ? (minutes + "分钟") : '')
}

// 获取地图scheme， 经纬度坐标类型要求为gcj02不然位置会有偏差from 从哪里
const getMapScheme = (from, to, mapType = "gaode") => {
    const u = navigator.userAgent;
    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端

    const andriodBaidu = (to) => {
        return `bdapp://map/direction?destination=name:${to.name}|latlng:${to.latitude},${to.longitude}&coord_type=gcj02&mode=driving&src=andr.jianghu.jianhao`
    }

    const iOSBaidu = (to) => {
        return `baidumap://map/direction?destination=name:${to.name}|latlng:${to.latitude},${to.longitude}&coord_type=gcj02&mode=driving&src=ios.jianghu.jianhao`
    }

    const andriodGaode = (to) => {
        return `amapuri://route/plan/?sourceApplication=mhc&dlat=${to.latitude}&dlon=${to.longitude}&dname=${to.name}&dev=0&t=0`
    }

    const iOSGaode = (to) => {
        return `iosamap://path?sourceApplication=mhc&dlat=${to.latitude}&dlon=${to.longitude}&dname=${to.name}&dev=0&t=0`
    }
    if (mapType == "baidu") {
        if (isAndroid) {
            return andriodBaidu(to)
        } else {
            return iOSBaidu(to)
        }
    } else if (mapType == "gaode") {
        if (isAndroid) {
            return andriodGaode(to)
        } else {
            return iOSGaode(to)
        }
    }
}
const autoPicture = async (el, options) => {
    let { scale = 3, allowTaint = false, useCORS = true, width = '375', height = '649', backgroundColor = null } = options
    const id = document.getElementById(el)
    const canvas = await html2canvas(id, {
        scale, //缩放比例,默认为1
        allowTaint, //是否允许跨域图像污染画布
        useCORS, //是否尝试使用CORS从服务器加载图像
        width, //画布的宽度
        height, //画布的高度
        backgroundColor //画布的背景色，默认为透明
    })
    let base64 = canvas.toDataURL('image/png')
    let u = navigator.userAgent;
    let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;   //判断是否是 android终端
    let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);     //判断是否是 iOS终端
    // var isAndroid = /android/i.test(navigator.userAgent);
    if (window.tp && isAndroid) {
        try {
            window.tp.saveImage({ url: base64 })
        } catch (error) {
            console.log(error)
        }
        return
    }
    try {
        canvas.toBlob(function (blob) {
            // 创建一个文件对象
            var downloadLink = document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(blob);
            console.log(downloadLink.href)
            downloadLink.download = `${new Date().getTime()}.png`;
            // 模拟点击下载链接
            document.body.appendChild(downloadLink);
            downloadLink.click();
            // 移除下载链接
            document.body.removeChild(downloadLink);
        }, 'image/png');
    } catch (error) {
        console.log(error, 1)
    }
}
//字符串转base64
function enBase64(str) {
    // 对字符串进行编码
    var encode = encodeURI(str);
    // 对编码的字符串转化base64
    var base64 = btoa(encode);
    return base64;
}

// base64转字符串
function deBase64(base64) {
    // 对base64转编码
    var decode = atob(base64);
    // 编码转字符串
    var str = decodeURI(decode);
    return str;
}
function jsonAbiToHumanReadable(jsonAbi) {
  const humanReadableAbi = jsonAbi.map((item) => {
    if (item.type === "function") {
      const inputs = item.inputs
        .map((input) => `${input.type} ${input.name}`)
        .join(", ");

      // 处理outputs，包含tuple和tuple[]类型
      const outputs = item.outputs
        .map((output) => {
          if (output.type.startsWith("tuple")) {
            const components = output.components
              .map((component) => `${component.type} ${component.name}`)
              .join(", ");
            return output.type.endsWith("[]")
              ? `(${components})[] ${output.name}`
              : `(${components}) ${output.name}`;
          }
          return `${output.type} ${output.name}`;
        })
        .join(", ");

      const returns = outputs ? `returns (${outputs})` : "";

      const viewModifier =
        item.stateMutability === "view" || item.stateMutability === "pure"
          ? " view"
          : "";
      const payableModifier =
        item.stateMutability === "payable" ? " payable" : "";
      const mutability = viewModifier || payableModifier || " nonpayable";

      return `function ${item.name}(${inputs})${mutability} ${returns}`;
    } else if (item.type === "event") {
      const inputs = item.inputs
        .map(
          (input) =>
            `${input.indexed ? "indexed " : ""}${input.type} ${input.name}`
        )
        .join(", ");
      return `event ${item.name}(${inputs})`;
    } else {
      return "";
    }
  });

  return humanReadableAbi.filter(Boolean);
}
export {
  formatDate,
  checkUrl,
  cutZero,
  getUrlParam,
  splitAddress,
  getDate,
  intervalTime,
  getMapScheme,
  autoPicture,
  getAudioVideo,
  enBase64,
  deBase64,
  jsonAbiToHumanReadable,
};

